package com.danieltoms.gcSync.util;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil
{
	public static Date parseRFC3339(String value)
	{
		Date d = null;

		int dash = value.indexOf('-');
		String year = value.substring(0, dash);
		int dash2 = value.indexOf('-', dash + 1);
		String month = value.substring(dash + 1, dash2);
		int t = value.indexOf('T');
		String day = value.substring(dash2 + 1, t);
		int col = value.indexOf(':');
		int col2 = value.indexOf(':', col + 1);
		String hour = value.substring(t + 1, col);
		String min = value.substring(col + 1, col2);
		String sec = value.substring(col2 + 1, value.indexOf('.'));

		int yeari = Integer.parseInt(year);
		int monthi = Integer.parseInt(month) - 1;
		int dayi = Integer.parseInt(day);
		int houri = Integer.parseInt(hour);
		int mini = Integer.parseInt(min);
		int seci = Integer.parseInt(sec);

		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		c.set(Calendar.YEAR, yeari);
		c.set(Calendar.MONTH, monthi);
		c.set(Calendar.DAY_OF_MONTH, dayi);
		c.set(Calendar.HOUR_OF_DAY, houri);
		c.set(Calendar.MINUTE, mini);
		c.set(Calendar.SECOND, seci);
		c.set(Calendar.MILLISECOND, 0);

		d = c.getTime();

		return d;
	}

	public static String formatRFC3339(Date d)
	{
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		c.setTime(d);

		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);

		StringBuffer buf = new StringBuffer();
		buf.append(year);
		buf.append("-");
		if (month < 10)
			buf.append('0');
		buf.append(month);
		buf.append("-");
		if (day < 10)
			buf.append('0');
		buf.append(day);
		buf.append('T');
		if (hour < 10)
			buf.append('0');
		buf.append(hour);
		buf.append(':');
		if (minute < 10)
			buf.append('0');
		buf.append(minute);
		buf.append(':');
		if (second < 10)
			buf.append('0');
		buf.append(second);
		// fake fractional seconds
		buf.append(".000Z");

		return buf.toString();

	}
}
